package nl.windgazer.arachne.services.yql;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.joda.time.DateTime;

public class YQLConduitCacheImp<T> implements Map<String, YQLConduitCacheVO<T>> {

	final private HashMap<String, YQLConduitCacheVO<T>> cache = new HashMap<String, YQLConduitCacheVO<T>>();
	final private long maxCacheDuration;

	/**
	 * i = max Cached duration in minutes.
	 * @param i
	 */
	public YQLConduitCacheImp(long i) {
		maxCacheDuration = i * 60 * 1000;
	}

	public int size() {
		return cache.size();
	}

	public boolean isEmpty() {
		return cache.isEmpty();
	}

	public boolean containsKey(Object key) {
		if (cache.containsKey(key)) {
			YQLConduitCacheVO<T> vo = cache.get(key);
			if ((new DateTime().getMillis() - vo.getAge().getMillis()) > maxCacheDuration) {
				cache.remove(key);
				return false;
			}
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public boolean containsValue(Object value) {
		if (cache.containsValue(value) && 
			(new DateTime().getMillis() - ((YQLConduitCacheVO<T>)value).getAge().getMillis()) > maxCacheDuration) {
			return true;
		}
		return false;
	}

	public YQLConduitCacheVO<T> get(Object key) {
		if (containsKey(key)) {
			return cache.get(key);
		}
		return null;
	}

	public YQLConduitCacheVO<T> put(String key, YQLConduitCacheVO<T> value) {
		return cache.put(key, value);
	}

	public YQLConduitCacheVO<T> remove(Object key) {
		return cache.remove(key);
	}

	public void putAll(Map<? extends String, ? extends YQLConduitCacheVO<T>> t) {
		cache.putAll(t);
	}

	public void clear() {
		cache.clear();
	}

	public Set<String> keySet() {
		return cache.keySet();
	}

	public Collection<YQLConduitCacheVO<T>> values() {
		return cache.values();
	}

	public Set<java.util.Map.Entry<String, YQLConduitCacheVO<T>>> entrySet() {
		return cache.entrySet();
	}

}
